package com.sofwin.service.impl;/**
 * @PackageName:com.sofwin.service.impl
 * @author:andyLiu
 * @DateTime:2020/12/28 16:32
 * @Description:[TODO]输入当前模块作用
 **/

import com.sofwin.dto.MenuDto;
import com.sofwin.dto.TreeNodeDto;
import com.sofwin.mapper.SResourceMapper;
import com.sofwin.mapper.SRoleresourceMapper;
import com.sofwin.pojo.SResource;
import com.sofwin.pojo.SRoleresource;
import com.sofwin.pojo.SRoleresourceExample;
import com.sofwin.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ResourceServiceImpl
 * @Description: TODO
 * @Author: andyliu
 * @Date: 2020/12/28 16:32
 * @Version: 1.0
 **/
@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    SResourceMapper mapper;
    @Autowired
    SRoleresourceMapper roleresourceMapper;

    @Override
    public List<TreeNodeDto> queryAll() {
        // 使用mapper去查询并封装数据
        return mapper.selectAll();
    }

    @Override
    public List<Map> queryAllResources() {
        List<Map> result = new ArrayList<Map>();
        List<SResource> sResources = mapper.selectByExample(null);
        for (SResource resource:sResources ) {
            Map map = new HashMap();
            map.put("id",resource.getId());
            map.put("pId",resource.getPid());
                map.put("open",resource.getPid()==0?true:false);

            map.put("name",resource.getResourceName());
            result.add(map);
        }
        return result;
    }

    @Override
    public List<SResource> queryAllResourceForJson() {
        return mapper.selectByExample(null);
    }

    @Override
    public boolean save(SRoleresource roleresource) {
        // 当前节点信息
        SResource sResource = selectById(roleresource.getResourceId());

        boolean isParent = sResource.getPid()==0?true:false;

        if(isParent){
            // 父处理
            boolean inDb = checkRoleIdAndResourceId(roleresource.getRoleId(), roleresource.getResourceId());
            if(inDb){
                // 存在需要删除
                deleteParentAndChild(roleresource.getRoleId(),roleresource.getResourceId());
            }else{
                // 不存在 插入
                saveParentAndChild(roleresource.getRoleId(),roleresource.getResourceId());
            }
        }else{
            // 子处理
            boolean inDb = checkRoleIdAndResourceId(roleresource.getRoleId(), roleresource.getResourceId());
            if(inDb){
                // 存在，需要删除
                boolean isLast = isLastChild(roleresource.getRoleId(),roleresource.getResourceId());
                if(isLast){
                    // 删除父+子

                    deleteParentAndChild(roleresource.getRoleId(),sResource.getPid());
                }else{
                    deleteById(roleresource.getRoleId(),roleresource.getResourceId());
                }
            }else{
                // 不存在 需要插入
                boolean isFirst = isFirstChild(roleresource.getRoleId(),roleresource.getResourceId());
                if(isFirst){
                    insertParentAndNode(roleresource.getRoleId(),roleresource.getResourceId());
                }else{
                    insertById(roleresource.getRoleId(),roleresource.getResourceId());
                }
            }
        }
        return true;
    }

    @Override
    public List<SResource> queryAllResourceByRoleId(Integer id) {
        return mapper.selectResourcesByRoleId(id);
    }

    @Override
    public List<MenuDto> queryResourcesByRoleId(Integer roleId) {
        return roleresourceMapper.selectResourcesByRoleId(roleId);
    }

    @Override
    public Boolean saveRoleResources(Integer[] ids, Boolean status, Integer roleId) {
       boolean flag = true;
       try {
           if (status) {
               // insert
               for (Integer id : ids) {
                   SRoleresource roleresource = new SRoleresource();
                   roleresource.setResourceId(id);
                   roleresource.setRoleId(roleId);
                   roleresourceMapper.insertSelective(roleresource);
               }
           } else {
               // delete
               for (Integer id : ids) {
                   SRoleresourceExample ex = new SRoleresourceExample();
                   SRoleresourceExample.Criteria criteria = ex.createCriteria();
                   criteria.andRoleIdEqualTo(roleId);
                   criteria.andResourceIdEqualTo(id);
                   roleresourceMapper.deleteByExample(ex);
               }
           }
       }catch (Exception ex){
           flag = false;
       }
        return flag;
    }

    @Override
    public List<String> selectRolePermission(Integer roleId) {
        return roleresourceMapper.selectRolePermissions(roleId);
    }

    /**
     *判断该节点是否存在
     * @param roleId
     * @param resourceId
     * @return true 代表有角色和资源id，
     *         false 代表没有角色和资源id
     */
    public boolean checkRoleIdAndResourceId(Integer roleId,Integer resourceId){
        SRoleresourceExample ex = new SRoleresourceExample();
        SRoleresourceExample.Criteria criteria = ex.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        criteria.andResourceIdEqualTo(resourceId);
        List<SRoleresource> sRoleresources = roleresourceMapper.selectByExample(ex);
        if(sRoleresources!=null && sRoleresources.size()>0){
            return true;
        }
        return false;
    }
    // 根据resourceId获取节点信息

    /**
     *
     * @param resourceId
     * @return pid ==0 为父
     */
    public SResource selectById(Integer resourceId){
        return mapper.selectByPrimaryKey(resourceId);
    }

    /**
     * 插入父+子
     * @param roleId
     * @param resourceId
     * @return
     */
    public boolean saveParentAndChild(Integer roleId,Integer resourceId) {
        boolean status = true;
        Map map = new HashMap();
        map.put("roleId", roleId);
        map.put("resourceId", resourceId);
        try{
        mapper.insertParentAndChildren(map);
        }catch(Exception ex){
        status = false;
        }
        return status;
    }

    /**
     * 删除父+子
     * @param roleId
     * @param resourceId  父节点的id
     * @return
     */
    public boolean deleteParentAndChild(Integer roleId,Integer resourceId){
        boolean status = true;
        try{
            Map map = new HashMap();
            map.put("roleId",roleId);
            map.put("resourceId",resourceId);
            mapper.deleteParentAndChildren(map);
        }catch (Exception ex){
            status = false;
        }
        return status;
    }

    /**
     * 是否为最后一个子节点
     * @param roleId
     * @param resourceId  -- 子节点id
     * @return
     */
    public boolean isLastChild(Integer roleId,Integer resourceId){
        SResource sResource = selectById(resourceId);
        Integer pId = sResource.getPid();
        Map map = new HashMap();
        map.put("roleId",roleId);
        map.put("resourceId",pId);
        int count = mapper.selectChildrenCount(map);
        return count==1?true:false;
    }

    /**
     * 删除自身
     * @param roleId
     * @param resourceId  子节点
     * @return
     */
    public boolean deleteById(Integer roleId,Integer resourceId){
        SRoleresource roleresource = new SRoleresource();
        SRoleresourceExample ex = new SRoleresourceExample();
        SRoleresourceExample.Criteria criteria = ex.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        criteria.andResourceIdEqualTo(resourceId);
        int flag = roleresourceMapper.deleteByExample(ex);
        return  flag==1?true:false;
    }

    /**
     * 是否为第一个子节点
      * @param roleId
     * @param resourceId  子节点id
     * @return
     */
    public boolean isFirstChild(Integer roleId,Integer resourceId){
        SResource sResource = selectById(resourceId);
        Integer pid = sResource.getPid();
        Map map = new HashMap();
        map.put("roleId",roleId);
        map.put("resourceId",pid);
        int count = mapper.selectChildrenCount(map);
        return count==0?true:false;
    }

    /**
     * 插入当前
     * @param roleId
     * @param resourceId  -- 子节点ID
     * @return
     */
    public boolean insertById(Integer roleId,Integer resourceId){
        SRoleresource roleresource = new SRoleresource();
        roleresource.setRoleId(roleId);
        roleresource.setResourceId(resourceId);
        int flag = roleresourceMapper.insertSelective(roleresource);
        return flag==1?true:false;
    }

    /**
     * 插入当前节点和 对应的父节点
     * @param roleId
     * @param resourceId  -- 子节点id
     * @return
     */
    public boolean insertParentAndNode(Integer roleId,Integer resourceId){
        SResource sResource = selectById(resourceId);
        Integer pid = sResource.getPid();
        int flag =0;
        SRoleresource parent = new SRoleresource();
        parent.setRoleId(roleId);
        parent.setResourceId(pid);
        flag+=roleresourceMapper.insertSelective(parent);
        SRoleresource child = new SRoleresource();
        child.setRoleId(roleId);
        child.setResourceId(resourceId);
        flag+=roleresourceMapper.insertSelective(child);
        return flag==2?true:false;
    }





}
